package com.zhhs.galaxyott.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.ipanel.chongqing.playlibrary.core.ActivityJumpManager;
import com.zhhs.galaxyott.Constant;
import com.zhhs.galaxyott.R;
import com.zhhs.galaxyott.adapters.MovieDetailAdapter;
import com.zhhs.galaxyott.beans.MovieDetailRecBean;
import com.zhhs.galaxyott.beans.PlayUrlBean;
import com.zhhs.galaxyott.http.api.RequestMaker;
import com.zhhs.galaxyott.httpVolley.base.ResponseListener;
import com.zhhs.galaxyott.httpVolley.response.EmptyResponse;
import com.zhhs.galaxyott.httpVolley.response.MovieDetailRecommendResponse;
import com.zhhs.galaxyott.httpVolley.response.MovieDetailResponse;
import com.zhhs.galaxyott.httpVolley.response.UniversalResponse;
import com.zhhs.galaxyott.httpVolley.response.getPayPlatformURLResponse;
import com.zhhs.galaxyott.sharepreference.SharedPrefHelper;
import com.zhhs.galaxyott.utils.Logs;

public class MovieDetailActivity extends Activity implements OnClickListener {

    GridView lvMovie;
    MovieDetailAdapter adapter;
    List<MovieDetailRecBean> listData = new ArrayList<MovieDetailRecBean>();

    private ImageView poster;
    private TextView poster_name, ename, watch_number, type, director_actor, introdution, operate_collect,
            operate_purchase, operate_vip;

    private int movieid;
    private double price;
    private SharedPrefHelper sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie_detail);

        sp = SharedPrefHelper.getInstance(this);
        movieid = getIntent().getIntExtra("movieid", 0);
        String vodId = getIntent().getStringExtra("vodId");
        Logs.logD("DEBUG_dt", "this is movieid : " + movieid);
        Logs.logD("DEBUG_dt", "this is vodId : " + vodId);
        if (movieid != 0) {
            Constant.paymovieId = movieid;
        } else if(vodId != null){
        	movieid = Integer.parseInt(vodId);
        }else{
        	movieid = Constant.paymovieId;
        }
        lvMovie = (GridView) findViewById(R.id.detail_grid_movie);
        initView();

        loadData();

        getPayresult();

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void getPayresult() {
        Intent intent = this.getIntent();

        Uri uri = intent.getData();
        String scheme = intent.getScheme();
        if (uri != null) {
            Logs.logD("DEBUG_R", "THIS IS getMovieDetail-->1");
            String host = uri.getHost();
            String path = uri.getPath();
            // String orderId = uri.getQueryParameter("orderId");
            // String paySeq = uri.getQueryParameter("paySeq");
            // String payState = uri.getQueryParameter("payState");
            // String payDesc = uri.getQueryParameter("payDesc");
            // String payType = uri.getQueryParameter("payType");

            // {
            // "orderId":"ANDROID1464837167888534033",
            // "paySeq":"9950000002100169",
            // "payState":"1",
            // "payDesc":"支付成功",
            // "payType":"20000001"
            // }

            String orderId = "ANDROID1464837167888534033";
            String paySeq = "9950000002100169";
            String payState = "1";
            String payDesc = "支付成功";
            String payType = "20000001";

            RequestMaker.getpayCallback(orderId, paySeq, payState, payDesc, payType,
                    new ResponseListener<EmptyResponse>() {

                        @Override
                        public void onResponse(EmptyResponse result) {
                            Logs.logD("DEBUG_DT", "THIS IS getpayCallback-->result:" + result);
                        }

                        @Override
                        public void onError(VolleyError error) {
                            Logs.logD("DEBUG_DT", "THIS IS getpayCallback-->ERR");
                        }
                    });

            Toast.makeText(
                    getApplicationContext(),
                    "请求地址：" + scheme + "://" + host + "/" + path + "，参数：orderId=" + orderId + "，paySeq=" + paySeq
                            + "，payState=" + payState + "，payDesc=" + payDesc + "，payType=" + payType,
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "参数为空", Toast.LENGTH_LONG).show();
        }

    }

    private void loadData() {
        getMovieDetail();
        getRecommandList();

    }

    private void getMovieDetail() {
        int pid = movieid;
        String smartcardid = sp.getsmartcard();

        RequestMaker.getMovieDetail(this, pid, smartcardid, new ResponseListener<MovieDetailResponse>() {

            @Override
            public void onResponse(MovieDetailResponse result) {

                if (result.Beans == null) {
                    return;
                }

                Logs.logD("DEBUG_DT", "THIS IS getMovieDetail-->" + result.errCode);
                if (result.errCode == 0) {
                    poster_name.setSelected(true);
                    ename.setSelected(true);
                    poster_name.setText(result.Beans.getName());
                    ename.setText(result.Beans.getEname());
                    watch_number.setText("共" + result.Beans.getWatchNum() + "人看过");
                    type.setText("类型:");
                    director_actor.setText("导演：" + result.Beans.getDirector() + "   " + "主演：" + result.Beans.getActor());
                    introdution.setText(result.Beans.getIntro());

                    price = result.Beans.getPrice();
                    operate_purchase.setText("单片" + price + "元");

                    // 判断是否购买
                    // if(){
                    // operate_purchase.setText("播放");
                    // operate_vip.setVisibility(View.GONE);
                    // }

                    Glide.with(MovieDetailActivity.this).load(result.Beans.getImgurl())
                            .placeholder(R.drawable.movie_detail_post_def).crossFade().into(poster);
                    if (result.Beans.getIsFavorite() >= 1) {
                        operate_collect.setText("取消收藏");
                    } else {
                        operate_collect.setText("收藏");
                    }

                }

            }

            @Override
            public void onError(VolleyError error) {
                Logs.logD("DEBUG_DT", "THIS IS getMovieDetail-->ERR");
            }
        });
    }

    private void getRecommandList() {
        int pageNo = 1;
        int pageRow = 100;

        RequestMaker.getMovieDetailRecommend(this, pageNo, pageRow,
                new ResponseListener<MovieDetailRecommendResponse>() {

                    @Override
                    public void onResponse(MovieDetailRecommendResponse result) {

                        if (result.Beans == null || result.Beans.size() == 0) {
                            return;
                        }

                        Logs.logD("DEBUG_DT", "THIS IS getMovieDetailRecommend-->ERR" + "size" + result.Beans.size());

                        if (result.errCode == 0) {

                            listData = result.Beans;

                            adapter = new MovieDetailAdapter(MovieDetailActivity.this, listData);
                            setGridView();
                        }
                    }

                    @Override
                    public void onError(VolleyError error) {
                        Logs.logD("DEBUG_DT", "THIS IS getMovieDetailRecommend-->ERR");
                    }
                });

    }

    private void initView() {

        poster = (ImageView) findViewById(R.id.movie_img);
        poster_name = (TextView) findViewById(R.id.poster_name);
        ename = (TextView) findViewById(R.id.ename);
        watch_number = (TextView) findViewById(R.id.watch_number);
        type = (TextView) findViewById(R.id.movie_type);
        director_actor = (TextView) findViewById(R.id.movie_director_actor);
        introdution = (TextView) findViewById(R.id.movie_introdution);

        operate_collect = (TextView) findViewById(R.id.operate_collect);
        operate_purchase = (TextView) findViewById(R.id.operate_purchase);
        operate_vip = (TextView) findViewById(R.id.operate_vip);

        lvMovie.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // TODO Auto-generated method stub
                operate_purchase.requestFocus();
            }
        });

        operate_collect.setOnClickListener(this);
        operate_purchase.setOnClickListener(this);
        operate_vip.setOnClickListener(this);
    }

    /** 设置GirdView参数，绑定数据 */
    private void setGridView() {
        int length = 125;
        int size = adapter.getCount();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        Logs.logD("DEBUG_d", "THIS IS density-->" + density);

        int gridviewWidth = (int) (size * (length + 0) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(gridviewWidth,
                LinearLayout.LayoutParams.MATCH_PARENT);
        lvMovie.setLayoutParams(params); // 设置GirdView布局参数,横向布局的关键
        lvMovie.setColumnWidth(itemWidth); // 设置列表项宽

        // 实现单行显示需要在代码中处理，如果使用xml中的“anto_fit”并没有用
        lvMovie.setNumColumns(size); // 设置列数量=列表集合数
        lvMovie.setAdapter(adapter);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.operate_collect:
            if (operate_collect.getText().toString().equals("收藏")) {
                operateCollect();
            } else {
                CancelCollect();
            }

            break;

        case R.id.operate_purchase:
            if (!Constant.isProducted) {
                return;
            }

            String progId = "SFYX201601061840" + "-SFYX";
            getUrl(progId);
            // payJump("");

            break;
        case R.id.operate_vip:
            if (!Constant.isProducted) {
                return;
            }

            payJump("");

            // Intent intent = new Intent();
            // intent.setClass(this, DeviceCenterActivity.class);
            // intent.putExtra("number", 0);
            // this.startActivity(intent);

            break;

        default:
            break;
        }

    }

    // typeId 栏目ID(如不知道栏目ID可传-1)
    // vodId 影片的ID(可传内部与外部ID)
    // playType 播放类型：1为电影,非1为剧集
    // baseFlag 0：包月，2：按次点播
    // idType 可选参数
    // 影片ID类型(如是外部ID需要把值设成FSN)
    private void getUrl(String progId1) {

        String typeId = "-1";
        // String progId = "CP23010020150425067200-WASU";
        // 免费(美国队长)
        // String progId = "SFYX201601061837" + "-sfyx";
        // 付费
        // String progId = "SFYX201603181216" + "-sfyx";
        String progId = "SFYX201601061842" + "-sfyx";
        // String progId =
        // "?typeId=-1&playType=1&progId=4428393&contentType=0&business=1" + "";
        String playType = "1";
        String idType = "FSN";
        String baseFlag = "2";

        String epg_url = sp.getepgUrl();
        // 外部Id
        String HttpUrl = epg_url + "/defaultHD/en/Auth_removeBase_nor.jsp?typeId=" + typeId + "&progId=" + progId
                + "&playType=" + playType + "&idType=" + idType + "&baseFlag=" + baseFlag
                + "&contentType=0&business=1&appBackUrl=";
        // 内部Id
        // String HttpUrl = epg_url +
        // "/defaultHD/en/go_authorization.jsp?typeId=" + typeId + "&progId=" +
        // progId
        // + "&playType=" + playType + "&baseFlag=" + baseFlag +
        // "&contentType=0&business=1&appBackUrl=";

        // String HttpUrl = epg_url + "/defaultHD/en/go_authorization.jsp"
        // + "?typeId=-1&playType=1&progId=4329190&contentType=0&business=1";

        // String HttpUrl = epg_url
        // +
        // "/defaultHD/en/ go_authorization.jsp?typeId=-1&progId=4436908&playType=1&baseFlag=0&contentType=0&business=1&appBackUrl= ";

        Logs.logD("DEBUG_LC", "THIS IS -->HttpUrl:" + HttpUrl);

        VolleyForGet(HttpUrl);

    }

    private synchronized void VolleyForGet(final String HttpUrl) {
        final PlayUrlBean result = new PlayUrlBean();

        StringRequest stringRequest = new StringRequest(Request.Method.GET, HttpUrl, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                try {
                    Logs.logD("DEBUG_LC", "THIS IS -->onResponse:" + response);
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject != null) {
                        result.setPlayFlag(jsonObject.optString("playFlag"));
                        result.setMessage(jsonObject.optString("message"));
                        result.setPlayUrl(jsonObject.optString("playUrl"));
                        result.setConfirmUrl(jsonObject.optString("confirmUrl"));

                        Logs.logD("DEBUG_LC", "THIS IS -->onResponse:getPlayFlag" + result.getPlayFlag() + "url:"
                                + result.getPlayUrl() + "confirmUrl:" + result.getConfirmUrl());

                        if (result.getConfirmUrl() != null && result.getConfirmUrl().length() > 0) {
                            VolleyForGet(result.getConfirmUrl());
                        } else if (result.getPlayFlag().equals("1") && result.getPlayUrl().length() > 1) {
                            playMovie(result.getPlayFlag());
                            // playMovie("rtsp://192.168.14.60/88888888/16/20160106/269921116/269921116.ts?rrsip=192.168.14.60&SRMSessionID=3448!746.000!2823!10208880001020193!9950000002100169!10.239.162.18&PurchaseToken=4186143&NetType=Cable&accountinfo=,9950000002100169,192.168.88.2,&SRMSIP=192.168.13.92&SRMSPORT=33700?/192.168.13.188:8082/7/746000/6875/64/MPEG-2");
                        } else {
                            // getPayPlatformUrlAndJump();
                            payJump("");
                        }

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Logs.logD("DEBUG_LC", "THIS IS -->getUrl:JSONException");
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                Logs.logD("DEBUG_LC", "THIS IS -->getUrl:err");
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Cookie", sp.getCookies());
                return headers;

            }

        };
        RequestQueue mQueue = Volley.newRequestQueue(MovieDetailActivity.this);
        mQueue.add(stringRequest);

    }

    private void playMovie(String url) {
        // String url =
        // "http://101.201.28.221:7070/suphomentSource/balijiaqi/balijiaqi@UD.mp4";
        String playType = "RTSP";
        Logs.logD("DEBUG_LC", "THIS IS -->operate_purchase");
        ActivityJumpManager.startToPlay(this, "传奇之战", url, playType);
    }

    // payChannel String 商户编码：ccn+16位字符串，如：ccnf82d132f9bb018ca
    // userName String 用户名 (选填)
    // orderId String 商户订单号
    // payAmount String 支付金额，单位（分）
    // targetId String 支付终端编号（机顶盒编号）
    // cardNo String 支付终端卡号（智能卡号）
    private void payJump(String playUrl) {
        ComponentName component = new ComponentName("com.crunii.ccn.tvhall",
                "com.crunii.ccn.tvhall.activity.PayActivity");
        Intent intent = new Intent();
        intent.setComponent(component);

        // intent.putExtra("payurl", playUrl);

        String orderId = "SFYX" + new Date().getTime() + ((int) ((Math.random() * 9 + 1) * 100000));
        String payAmount = "1";
        String targetId = sp.getStbid();
        String cardNo = sp.getsmartcard();

        intent.putExtra("payurl", "http://192.168.5.74:9000/ccn-pay/payPlatform" + "?payChannel="
                + "ccn1ec48caab3179e60" + "&userName= " + "&orderId=" + orderId + "&payAmount=" + payAmount
                + "&targetId=" + targetId + "&cardNo=" + cardNo + "&extend=充值缴费"
                + "&notifyUrl= http://192.168.5.73/ccn-tv/cz/notify" + "&homeUrl=myccntvhall://platformapi/home"
                + "&returnUrl=myccntvhall://platformapi/return" + "&rechargeType=1&rechargeAccount=0");

        this.startActivity(intent);
        this.finish();
    }

    private void getPayPlatformUrlAndJump() {

        String orderId = "SFYX" + new Date().getTime() + ((int) ((Math.random() * 9 + 1) * 100000));
        Double payAmount = 1.0;
        String targetId = sp.getStbid();
        String cardNo = sp.getsmartcard();

        String returnUrl = "ccntvhall://platformapi/return";
        String homeUrl = "";
        String playUrl = "";

        RequestMaker.getPayPlatformURL(targetId, cardNo, payAmount, returnUrl, homeUrl,
                new ResponseListener<getPayPlatformURLResponse>() {

                    @Override
                    public void onResponse(getPayPlatformURLResponse result) {
                        Logs.logD("DEBUG_DT", "THIS IS getPayPlatformURL-->" + result.errCode + result.getPayurl());
                        if (result != null && result.errCode == 0) {

                            String playUrl = result.getPayurl();

                            payJump(playUrl);
                        } else {
                            Toast.makeText(MovieDetailActivity.this, "请求失败，请重试", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(VolleyError error) {
                        Logs.logD("DEBUG_DT", "THIS IS getPayPlatformURL-->ERR");
                        Toast.makeText(MovieDetailActivity.this, "请求错误", Toast.LENGTH_SHORT).show();
                    }
                });

    }

    private void operateCollect() {

        int pid = movieid;
        String smartcardid = sp.getsmartcard();
        RequestMaker.addCollected(this, pid, smartcardid, new ResponseListener<UniversalResponse>() {

            @Override
            public void onResponse(UniversalResponse result) {
                Logs.logD("DEBUG_DT", "THIS IS addCollected-->" + result.errCode);
                if (result.errCode == 0) {
                    operate_collect.setText("取消收藏");
                }

            }

            @Override
            public void onError(VolleyError error) {
                Logs.logD("DEBUG_DT", "THIS IS addCollected-->ERR");

            }
        });

    }

    private void CancelCollect() {

        int pid = movieid;
        String smartcardid = sp.getsmartcard();
        RequestMaker.delCollected(this, pid, smartcardid, new ResponseListener<UniversalResponse>() {

            @Override
            public void onResponse(UniversalResponse result) {
                Logs.logD("DEBUG_DT", "THIS IS delCollected-->" + result.errCode);
                if (result.errCode == 0) {
                    operate_collect.setText("收藏");
                } else {
                    Toast.makeText(getApplication(), "收藏失败", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onError(VolleyError error) {
                Logs.logD("DEBUG_DT", "THIS IS delCollected-->ERR");

            }
        });

    }
}
